﻿using System;
using System.Collections.Generic;
using System.Windows.Forms;
using HiStaff.Domain.Sys;
using HiStaff.Domain;
using HiStaff.iSystem;
using HiStaff.Util;
using HiStaff.Control;
using Janus.Windows.GridEX;
using System.Data;
using System.Linq;

namespace HiStaff.Base
{
    public partial class BaseList : FormBase
    {
        private string _lstData { get; set; }
        DataTable dtDel;
        List<SY_COLUMNS_LIST> dataCol;
        public BaseList()
        {
            InitializeComponent();
        }
        protected override bool FormLoad()
        {
            base.CreateCommandBar(CommandBarManager.ActionCommand.Edit,
                CommandBarManager.ActionCommand.Separator,
                CommandBarManager.ActionCommand.Save,
                CommandBarManager.ActionCommand.Cancel,
                CommandBarManager.ActionCommand.Delete,
                CommandBarManager.ActionCommand.Separator,
                CommandBarManager.ActionCommand.Exit);
            BindListData();
            SetToolStripButtonBar(CommandBarManager.ActionCommand.Cancel);
            return true;
        }
        private void BindListData()
        {
            List<SY_TAB_LIST> data = Service.SystemClient.GetDataListByUser(StaticObject.USERNAME);
            grdList.DataSource = data;
            grdList.Refresh();
        }
        private void CreateGirdData()
        {
            dataCol = Service.SystemClient.GetColumnList(_lstData);
            grdData.RootTable.Columns.Clear();
            grdData.GroupByBoxVisible = false;
            GridEXColumn col;
            
            foreach (SY_COLUMNS_LIST item in dataCol)
            {
                col = new GridEXColumn();
                col.Key = item.COLUMN_NAME;
                col.DataMember = item.COLUMN_NAME;
                col.Caption = item.DESCRIPTION;
                col.HeaderToolTip = item.DESCRIPTION;
                if (item.COLUMN_NAME == "ID")
                {
                    col.EditType = EditType.NoEdit;
                    col.FilterEditType = FilterEditType.TextBox;
                    col.ColumnType = ColumnType.Text;
                    col.TextAlignment = TextAlignment.Far;
                    col.Width = 30;
                }
                else
                {
                    switch (item.DATA_TYPE.ToString())
                    {
                        case "1":
                            col.EditType = EditType.TextBox;
                            col.Width = 80;
                            col.ColumnType = ColumnType.Text;
                            col.TextAlignment = TextAlignment.Far;
                            col.FormatString = "#,##0.##";
                            break;
                        case "2":
                            col.EditType = EditType.TextBox;
                            col.Width = 150;
                            col.ColumnType = ColumnType.Text;
                            break;
                        case "3":
                            col.EditType = EditType.CalendarCombo;
                            col.FormatString = "d";
                            col.Width = 100;
                            col.ColumnType = ColumnType.Text;
                            break;
                        case "4":
                            col.EditType = EditType.CheckBox;
                            col.ColumnType = ColumnType.CheckBox;
                            col.Width = 40;
                            col.CheckBoxFalseValue = 0m;
                            col.CheckBoxTrueValue = 1m;
                            col.CheckBoxTriState = false;
                            col.TextAlignment = TextAlignment.Center;
                            break;
                        case "5":
                            col.EditType = EditType.DropDownList;
                            col.ColumnType = ColumnType.Text;
                            col.Width = 150;
                            if (!string.IsNullOrEmpty(item.LIST_DATA))
                            {
                                List<SY_DEFAULT_LIST> lstData = Service.SystemClient.GetDataListReturnDefault(Constant.PREFIX_PROC_SELECT + item.LIST_DATA);
                                var sy = (from obj in lstData
                                          where obj.STATUS == 1
                                          select obj).ToList();
                                col.HasValueList = true;
                                col.ValueList.PopulateValueList(sy,
                                    Constant.COL_ID, Constant.COL_NAME);
                            }
                            break;
                        default:
                            col.EditType = EditType.TextBox;
                            col.ColumnType = ColumnType.Text;
                            col.Width = 100;
                            break;
                    }
                }
                col.FilterEditType = FilterEditType.SameAsEditType;
                grdData.RootTable.Columns.Add(col);
                if (item.DATA_TYPE.ToString()== "5")
                {
                    grdData.RootTable.Groups.Add(col, Janus.Windows.GridEX.SortOrder.Ascending);
                    grdData.GroupByBoxVisible = true;
                }
            }
        }
        private void BindColumComboBox()
        {
            foreach (SY_COLUMNS_LIST item in dataCol)
            {
                switch (item.DATA_TYPE.ToString())
                {
                    case "5":
                        var count = (from obj in dataCol
                                     where obj.CHILD_COL == item.COLUMN_NAME
                                     select obj).Count();
                        if (count > 0 && !string.IsNullOrEmpty(item.LIST_DATA))
                        {
                                List<SY_DEFAULT_LIST> lstData = Service.SystemClient.GetDataListReturnDefault(Constant.PREFIX_PROC_SELECT + item.LIST_DATA);
                                var sy = (from obj in lstData
                                          where obj.STATUS == 1
                                          select obj).ToList();
                                grdData.RootTable.Columns[item.COLUMN_NAME].ValueList.PopulateValueList(sy,
                                    Constant.COL_ID, Constant.COL_NAME);
                        }
                        break;
                }
            }
        }
        private void BindGridData()
        {
            DataTable dt = Service.ExcuteStoreToDataTable(Constant.PREFIX_PROC_SELECT + _lstData);
            dtDel = dt.Clone();
            grdData.DataSource = dt;
            grdData.Refresh();
        }
        private void grdList_SelectionChanged(object sender, EventArgs e)
        {
            if (grdList.SelectedItems.Count == 0) return;
            GridEXSelectedItem row = grdList.SelectedItems[0];
            if (row.RowType == RowType.Record)
            {
                SY_TAB_LIST dataItem = (SY_TAB_LIST)row.GetRow().DataRow;
                _lstData = dataItem.TABLE_NAME;
                CreateGirdData();
                BindGridData();
            }
        }
        protected override bool AddNewButtonClick()
        {
            grdData.AllowAddNew = InheritableBoolean.True;
            grdData.AllowEdit = InheritableBoolean.True;
            return true;
        }
        protected override bool CancelButtonClick()
        {
            grdData.AllowAddNew = InheritableBoolean.False;
            grdData.AllowEdit = InheritableBoolean.False;
            BindGridData();
            return true;
        }
        protected override bool EditButtonClick()
        {
            grdData.AllowAddNew = InheritableBoolean.True;
            grdData.AllowEdit = InheritableBoolean.True;
            return true;
        }
        protected override void SetToolStripButtonBar(CommandBarManager.ActionCommand cmd)
        {
            switch (cmd)
            {
                case CommandBarManager.ActionCommand.Edit:
                    SetEnabledCommandSave = true;
                    SetEnabledCommandDelete = true;
                    SetEnabledCommandCancel = true;
                    SetEnabledCommandEdit = false;
                    break;
                case CommandBarManager.ActionCommand.Cancel:
                case CommandBarManager.ActionCommand.Save:
                    SetEnabledCommandSave = false;
                    SetEnabledCommandDelete = false;
                    SetEnabledCommandCancel = false;
                    SetEnabledCommandEdit = true;
                    break;
            }
        }
        protected override bool SaveButtonClick()
        {
            ExcuteAsynchronous();
            grdData.AllowAddNew = InheritableBoolean.False;
            grdData.AllowEdit = InheritableBoolean.False;
            return true;
        }
        protected override bool DeleteButtonClick()
        {
            if (grdData.SelectedItems.Count == 0) return false;
            GridEXSelectedItem item = grdData.SelectedItems[0];
            if (item.RowType == RowType.Record)
            {
                DataRow dr = ((DataRowView)item.GetRow().DataRow).Row;
                if (dr[Constant.COL_ID] != DBNull.Value)
                    dtDel.ImportRow(dr);
                ((DataTable)grdData.DataSource).Rows.Remove(dr);
                grdData.Refresh();
            }
            return true;
        }
        protected override bool CalculateButtonClick()
        {
            BindGridData();
            return true;
        }
        protected override bool AsynchronousFunctionWithBGW(System.ComponentModel.BackgroundWorker bgWorker)
        {
            DataTable dt = (DataTable)grdData.DataSource;
            int i = 3;
            int j = 0;
            int percent;

            j++;
            Service.ExcuteStoreNonQuery(Constant.PREFIX_PROC_DELETE + _lstData, dtDel);
            percent = (j * 100 / i);
            bgWorker.ReportProgress(percent, "Đang thực hiện");

            j++;
            Service.ExcuteStoreNonQuery(Constant.PREFIX_PROC_UPDATE + _lstData, dt);
            percent = (j * 100 / i);
            bgWorker.ReportProgress(100, "Hoàn tất");
            return true;
        }

        private void menuGrdList_ItemClicked(object sender, ToolStripItemClickedEventArgs e)
        {
            AddListData frmAdd;
            switch (e.ClickedItem.Tag.ToString())
            {
                case "Add":
                    frmAdd = new AddListData();
                    frmAdd.ShowDialog();
                    BindListData();
                    frmAdd.Close();
                    break;
                case "Edit":
                    frmAdd = new AddListData();
                    frmAdd.ListDataEdit = _lstData;
                    frmAdd.ShowDialog();
                    BindListData();
                    frmAdd.Close();
                    break;
            }
        }

        private void grdData_UpdatingCell(object sender, UpdatingCellEventArgs e)
        {
            var col = (from obj in dataCol
                       where obj.COLUMN_NAME == e.Column.Key
                       select obj).FirstOrDefault();
            
            if (!string.IsNullOrEmpty(col.CHILD_COL))
            {
                var item = (from obj in dataCol
                            where obj.COLUMN_NAME == col.CHILD_COL
                            select obj).FirstOrDefault();
                
                DataTable dt = Service.ExcuteStoreToDataTable(Constant.PREFIX_PROC_SELECT + item.LIST_DATA);
                DataTable dtTemp = dt.Clone();
                DataRow[] dr = dt.Select("STATUS = 1 AND " + e.Column.Key + " = " + e.Value);
                foreach (DataRow d in dr)
                {
                    dtTemp.ImportRow(d);
                }
                List<SY_DEFAULT_LIST> lstData = ConvertHelper.DataTableToList<SY_DEFAULT_LIST>(dtTemp);
                foreach (GridEXCell cell in grdData.SelectedItems[0].GetRow().Cells)
                {
                    if (cell.Column.Key == col.CHILD_COL)
                    {
                        cell.ValueList.PopulateValueList(lstData, Constant.COL_ID, Constant.COL_NAME);
                        cell.Value = DBNull.Value;
                        break;
                    }
                }
            }
        }

        private void grdData_AddingRecord(object sender, System.ComponentModel.CancelEventArgs e)
        {
            BindColumComboBox();
        }
        private void grdData_UpdatingRecord(object sender, System.ComponentModel.CancelEventArgs e)
        {
            BindColumComboBox();
        }

        private void grdData_EditingCell(object sender, EditingCellEventArgs e)
        {
            if (grdData.SelectedItems[0].RowType != RowType.NewRecord)
            {
                var lst = (from obj in dataCol
                           where obj.CHILD_COL == e.Column.Key
                           select obj).FirstOrDefault();
                if (lst != null)
                {
                    var list_data = (from obj in dataCol
                                     where obj.COLUMN_NAME == e.Column.Key
                                     select obj.LIST_DATA).FirstOrDefault();
                    DataTable dt = Service.ExcuteStoreToDataTable(Constant.PREFIX_PROC_SELECT + list_data);
                    DataTable dtTemp = dt.Clone();
                    DataRow[] dr = dt.Select("STATUS = 1 AND " + lst.COLUMN_NAME + " = " + grdData.SelectedItems[0].GetRow().Cells[lst.COLUMN_NAME].Value);
                    foreach (DataRow d in dr)
                    {
                        dtTemp.ImportRow(d);
                    }
                    List<SY_DEFAULT_LIST> lstData = ConvertHelper.DataTableToList<SY_DEFAULT_LIST>(dtTemp);
                    e.Column.ValueList.PopulateValueList(lstData, Constant.COL_ID, Constant.COL_NAME);
                }
            }
        }
    }
}
